<template>
  <div v-loading="infoLoading">
    <el-dialog
      :title="fileDialogTitle"
      :visible.sync="fileDialogVisible"
      width="98%"
      top="20px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <el-form ref="filePostForm" :model="filePostForm" class="form-container" label-width="200px">
        <el-form-item v-if="!readOnly" label="文件" prop="file">
          <el-upload
            class="upload-demo"
            :action="this.$http.defaults.baseURL+'api/gen/file/upload/'"
            :on-success="handleUploadSucc"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-error="uploadError"
            :multiple="false"
            :file-list="fileList"
            :headers="myHeaders"
            :limit="1"
            :on-exceed="handleExceed"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="说明" prop="address">
          <el-input v-model="filePostForm.remark" type="textarea" style="width:800px" rows="10" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="submitFileForm">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-alert
      v-if="postForm.shzt===3"
      title="审核未通过"
      type="error"
      :description="'原因：'+hist.auditResult?hist.auditResult:'读取中...'"
      show-icon
    />
    <div v-if="showDuban">
      <supervise v-if="showSupervise()" business-table="bus_sfsj" :cfajbh="cfajbh" :timestamp="timestamp" />
    </div>
    <h2>司法审计</h2>
    <div v-if="readOnly&&!postForm.id" style="color:red;font-weight:bolder;margin-left:20px;">未录入</div>
    <el-form v-else ref="postForm" :model="postForm" :rules="rules" class="form-container" :inline="true">
      <table cellspacing="0" cellpadding="0" border="0" class="formTable" style="margin-bottom:10px;">
        <tr>
          <th>审计公司</th>
          <td>
            <el-form-item label="" prop="sjgs">
              <el-input v-if="!readOnly" v-model.trim="postForm.sjgs" style="width:350px" />
              <span v-else>{{ postForm.sjgs }}</span>
            </el-form-item>
          </td>
          <th>审计负责人</th>
          <td>
            <el-form-item label="" prop="sjfzr">
              <el-input v-if="!readOnly" v-model.trim="postForm.sjfzr" style="width:200px" />
              <span v-else>{{ postForm.sjfzr }}</span>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <th>司法审计<br>开始时间</th>
          <td>
            <el-form-item label="" prop="sfsjkssj">
              <el-date-picker v-if="!readOnly" v-model.trim="postForm.sfsjkssj" style="width:200px" value-format="yyyy-MM-dd" />
              <span v-else>{{ postForm.sfsjkssj }}</span>
            </el-form-item>
          </td>
          <th>是否出具最<br>终审计报告</th>
          <td>
            <el-form-item label="" prop="sfcjzzsjbg">
              <el-radio-group v-if="!readOnly" v-model="postForm.sfcjzzsjbg">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
              <span v-else>{{ postForm.sfcjzzsjbg?'是':'否' }}</span>
            </el-form-item>
          </td>
        </tr>
        <tr v-if="postForm.sfcjzzsjbg">
          <th>出具最终审<br>计报告时间</th>
          <td colspan="3">
            <el-form-item label="" prop="zzsjbg">
              <el-date-picker v-if="!readOnly" v-model.trim="postForm.zzsjbg" style="width:200px" value-format="yyyy-MM-dd" />
              <span v-else>{{ postForm.zzsjbg }}</span>
            </el-form-item>
          </td>
        </tr>
        <tr v-else>
          <th>未出具最终<br>审计报告原因</th>
          <td colspan="3">
            <el-form-item label="" prop="wcjzzsjbgyy">
              <el-input v-if="!readOnly" v-model.trim="postForm.wcjzzsjbgyy" style="width:610px" />
              <span v-else>{{ postForm.wcjzzsjbgyy }}</span>
            </el-form-item>
          </td>
        </tr>
      </table>
      <!-- <div>
        <upload-files v-if="!infoLoading" :cfajbh="postForm.cfajbh" :read-only="readOnly" table="bus_sfsj" :timestamp="timestamp" @updateFj="updateFj" />
      </div> -->
      <el-form-item style="margin:10px 0">
        <el-button v-if="!readOnly" type="warning" :loading="loading" @click="submitForm(0)">办理中</el-button>
        <el-button v-if="!readOnly" type="success" :loading="loading" @click="submitForm(1)">已完成</el-button>
      </el-form-item>
    </el-form>

    <el-form v-if="auditFlag" ref="auditForm" :model="auditForm" class="form-container" label-width="200px">
      <el-form-item label="是否通过" prop="auditState">
        <el-radio-group v-model="auditForm.auditState">
          <el-radio :label="1">通过</el-radio>
          <el-radio :label="0">未通过</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="auditFlag&&!auditForm.auditState" label="未通过原因" prop="auditResult">
        <el-input v-model="auditForm.auditResult" style="width:810px" />
      </el-form-item>
      <el-form-item style="margin:10px 0">
        <el-button type="success" :loading="loading" @click="submitAudit">审核</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>

// import uploadFiles from './uploadfiles.vue'
import supervise from './supervise.vue'
const defaultForm = {
  sjgs: '',
  sjfzr: '',
  sfsjkssj: '',
  cbsjbgsj: '',
  sfcjzzsjbg: '',
  zzsjbg: '',
  wcjzzsjbgyy: '',
  id: null
}
const defaultFileForm = {
  fileid: 0,
  remark: ''
}
const defaultAuditForm = {
  auditResult: '',
  auditState: 1
}
export default {
  name: 'ArticleDetail',
  components: {
    // uploadFiles,
    supervise
  },
  props: {
    readOnly: {
      type: Boolean,
      default: false
    },
    showDuban: {
      type: Boolean,
      default: false
    },
    cfajbh: {
      type: String,
      default: ''
    },
    timestamp: {
      type: Number,
      default: 0
    },
    step: {
      type: String,
      default: ''
    }
  },
  data() {
    // const validateRequire = (rule, value, callback) => {
    //   if (value === null || value === undefined || value === '') {
    //     // this.$message({
    //     //   message: '请将表单填写完整',
    //     //   type: 'error'
    //     // })
    //     callback(new Error('必填项'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      hist: {},
      auditFlag: false,
      auditForm: Object.assign({}, defaultAuditForm),
      fjloading: false,
      fjindex: -1,
      fileList: [],
      fjlList: [],
      fjList: [],
      fileDialogVisible: false,
      fileDialogTitle: '新增',
      myid: 0,
      roleName: '',
      deptName: '',
      realName: '',
      myHeaders: {},
      imageUrl: '',
      infoLoading: false,
      postForm: Object.assign({}, defaultForm),
      filePostForm: Object.assign({}, defaultFileForm),
      loading: false,
      deptOption: [],
      userOption: [],
      processUserOption: [],
      priorityOption: [],
      classCodeOption: [],
      flowTypeOption: [],
      rules: {
      },
      processListLoading: false,
      processList: [{ time: '第一次', unit1: '处非办', unit2: '公安局', date: '2021-05-10', limit: '10天', item: '尽快办理', result: '已办结' }, { time: '第二次', unit1: '处非办', unit2: '公安局', date: '2021-05-20', limit: '10天', item: '尽快办理', result: '已办结' }],
      processNow: {},
      mystep: ''
    }
  },
  watch: {
    timestamp: {
      handler(val, oldVal) {
        if (this.$refs['postForm']) {
          this.$refs['postForm'].resetFields()
        }
        this.mystep = this.step
        this.getData(this.cfajbh)
      },
      immediate: true
    }
  },
  mounted() {
    this.myHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
    const day = new Date()
    day.setTime(day.getTime())
    console.log(JSON.parse(localStorage.getItem('user')))
    this.roleName = JSON.parse(localStorage.getItem('user')).roleName
    // this.postForm.publishTime = day.getFullYear() + '-' + this.add0(day.getMonth() + 1) + '-' + this.add0(day.getDate())
  },
  created() {
  },
  methods: {
    showSupervise() {
      return true
      // return JSON.parse(localStorage.getItem('user')).unitName === '处非办' || JSON.parse(localStorage.getItem('user')).unitName === '公安' || JSON.parse(localStorage.getItem('user')).unitName === '督查室' || JSON.parse(localStorage.getItem('user')).unitName === '政法委'
    },
    // 提交审核
    submitAudit() {
      // if (this.auditForm.auditState === 0 && this.auditForm.auditResult === '') {
      //   this.$message({
      //     message: '审核不通过请说明原因',
      //     type: 'error'
      //   })
      // } else {
      const para = {
        id: this.postForm.id,
        auditResult: this.auditForm.auditResult,
        auditState: this.auditForm.auditState
      }
      this.loading = true
      this.$http
        .post('/api/busSfsj/audit', para)
        .then(response => {
          this.loading = false
          if (response.data.success === true) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.$emit('dialogHide')
            this.auditForm = Object.assign({}, defaultAuditForm)
            this.loading = false
            this.$router.back()
          } else {
            console.log('操作失败:' + response.data.message)
            this.$message({
              message: '操作失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.loading = false
        })
      // }
    },
    updateFj(list) {
      this.fjList = list
    },
    download(item) {
      window.open(this.$http.defaults.baseURL + 'api/gen/file/download?id=' + item.id)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`一次最多只能上传一个文件`)
    },
    uploadError(err) {
      console.log(err)
      this.$message({
        message: '上传失败:' + err,
        type: 'error',
        duration: 10000
      })
    },
    handleUploadSucc(response, file, fileList) {
      if (response.success) {
        this.$message({
          type: 'success',
          message: '上传成功!'
        })
        this.fileList.push({ id: response.result[0].id, name: response.result[0].fileName + '.' + response.result[0].fileType, url: this.$http.defaults.baseURL + 'api/gen/file/download?id=' + response.result[0].id, dataCreateDatetime: response.result[0].dataCreateDatetime })
      } else {
        this.$message({
          message: '上传失败:' + response.message,
          type: 'error',
          duration: 10000
        })
      }
    },
    dateFormat(date) {
      console.log('日期转换')
      console.log(date)
      return date.getFullYear().toString() + '-' + (date.getMonth() + 1).toString() + '-' + date.getDate().toString()
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      const fid = file.id
      this.$http.get('api/gen/file/remove?id=' + fid).then(res => {
        if (res.data.success === true) {
          this.fileList = this.fileList.filter(item => item.id !== fid)
          this.$message({
            message: '删除成功！',
            type: 'success'
          })
        }
      })
    },
    handleDeleteFile(index) {
      this.fjList.splice(index, 1)
    },
    submitFileForm() {
      if (this.fileList && this.fileList.length > 0) {
        console.log(this.fileList)
        this.fileList[0].remark = this.filePostForm.remark
        this.filePostForm = Object.assign({}, defaultFileForm)
        if (this.fjindex === -1) {
          this.fjList.push(this.fileList[0])
        } else {
          this.fjList[this.fjindex] = this.fileList[0]
          this.fjindex = -1
        }
        this.fileList = []
        this.fileDialogVisible = false
      } else {
        this.$message({
          message: '请上传文件',
          type: 'error'
        })
      }
    },
    editFile(index, item) {
      this.fileList = []
      this.fileList.push(item)
      this.filePostForm.remark = item.remark
      this.filePostForm.dataCreateDatetime = item.dataCreateDatetime
      this.fjindex = index
      this.fileDialogVisible = true
      this.fileDialogTitle = '修改'
    },
    addFile() {
      this.filePostFormForm = Object.assign({}, defaultFileForm)
      this.fileDialogVisible = true
      this.fileDialogTitle = '新增'
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      console.log('test')
      if (res.success) {
        this.$message({
          message: '上传成功！',
          type: 'success'
        })
        this.imageUrl = res.result[0].id
        // this.fileList = []
        // this.files = []
      } else {
        this.$message({
          message: '上传失败:' + res.message,
          type: 'error'
        })
      }
    },
    getFj(id) {
      const para = {
        pageNum: 1,
        pageSize: 1000,
        cfajbh: id,
        businessTable: 'bus_sfsj'
      }
      this.fjloading = true
      this.$http
        .post('/api/gen/file/search', para)
        .then(response => {
          this.loading = false
          if (response.data.success === true) {
            this.fjList = response.data.result.records.map(item => { return { name: item.fileName + '.' + item.fileType, remark: item.remark, id: item.id, dataCreateDatetime: item.dataCreateDatetime } })
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(function(error) {
          console.log(error)
          this.fjloading = false
        })
    },
    getHist() {
      const para = {
        actName: '司法审计',
        actState: 1,
        cfajbh: this.postForm.cfajbh,
        pageNum: 1,
        pageSize: 1
        // publishTime: this.listQuery.publishTime,
        // title: this.listQuery.title
      }
      this.$http
        .post('/api/busHist/queryByPage', para)
        .then(response => {
          if (response.data.success === true) {
            this.hist = response.data.result.records[0]
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getData(cfajbh) {
      this.infoLoading = true
      if (cfajbh) {
        this.$http
          .get('/api/busSfsj/getSfsjById?&cfajbh=' + cfajbh)
          .then(response => {
            this.infoLoading = false
            if (response.data.success === true) {
              if (response.data.result.sjgs) {
                console.log(response.data.result)
                this.postForm = response.data.result

                const userinfo = JSON.parse(localStorage.getItem('user'))
                const unitName = userinfo.unitName
                const roleName = userinfo.roleName
                if (response.data.result.shzt === 1 && unitName === '公安' && roleName === '审核') {
                  this.auditFlag = true
                } else {
                  this.auditFlag = false
                }
                if (response.data.result.shzt === 3) {
                  this.getHist()
                }
              } else {
                this.postForm = Object.assign({}, defaultForm)
              }
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.infoLoading = false
          })
      } else {
        this.$nextTick(() => {
          this.infoLoading = false
          this.postForm = Object.assign({}, defaultForm)
        })
      }
    },
    submitForm(flag) {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          const para = {
            // id: this.postForm.id ? this.postForm.id : null,
            cfajbh: this.cfajbh,
            sjgs: this.postForm.sjgs,
            sjfzr: this.postForm.sjfzr,
            sfsjkssj: this.postForm.sfsjkssj,
            cbsjbgsj: this.postForm.cbsjbgsj,
            sfcjzzsjbg: this.postForm.sfcjzzsjbg,
            zzsjbg: this.postForm.zzsjbg,
            wcjzzsjbgyy: this.postForm.wcjzzsjbgyy,
            files: this.fjList.map(item => { return { fileId: item.id, remark: item.remark, classCode: item.classCode } }),
            shzt: flag
          }
          this.loading = true
          this.$http
            .post('/api/busSfsj/saveSfsj', para)
            .then(response => {
              this.loading = false
              if (response.data.success === true) {
                this.$message({
                  message: '保存成功',
                  type: 'success'
                })
                this.$emit('dialogHide')
                this.postForm = Object.assign({}, defaultForm)
                this.loading = false
                this.$router.back()
              } else {
                console.log('保存失败:' + response.data.message)
                this.$message({
                  message: '保存失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(function(error) {
              console.log(error)
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.formTable{
  border-top:1px solid #dfe6ec;
  border-left:1px solid #dfe6ec;
  width: 100%;
}
.formTable td{
  border-bottom:1px solid #dfe6ec;
  border-right:1px solid #dfe6ec;
  margin:0;
  min-width: 500px;
  vertical-align: middle;
}
.formTable td div.el-form-item{
  font-size:14px;
  margin-top:22px;
  margin-left:20px;
}
.formTable th{
  font-size:14px;
  border-bottom:1px solid #dfe6ec;
  border-right:1px solid #dfe6ec;
  margin:0;
  width: 100px;
  background:#F5F7FA;
  line-height: 150%;
}
</style>
